/**
 * Created by wangkaihua on 2018/9/5.
 */

import React from 'react'
import { nodeTypes, approverTypes } from 'components/simple-flow/node-list'
import { connect } from 'react-redux'
import { setApproveRequest } from "actions/cache";
import { messages, deepFullCopy, dealCache } from "share/common";
import { Form, Modal, Icon, message, Spin } from 'antd'
import FullScreen from 'components/full-screen'
import NewWorkflowDetail from 'containers/setting/new-workflow/detail/workflow-detail'
import adminApproveListService from 'containers/setting/process-monitoring-platform/admin-approve-list.service'
import 'styles/setting/process-monitoring-platform/admin-skip.scss'
import 'styles/approve/request/request.scss'
import { allNodeList } from "components/simple-flow/node-list";
import manApprovalImg from 'images/setting/workflow/man-approval.svg'
import knowImg from 'images/setting/workflow/know.svg'
import aiApprovalImg from 'images/setting/workflow/aiapproval.svg'
import mailImg from 'images/setting/workflow/mail.png'
import auditImg from 'images/setting/workflow/audit.png'
import creditImg from 'images/setting/workflow/credit.svg'
import endImg from 'images/setting/workflow/end.png'

class AdminSkip extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showAdminSkipModal: false,
      showNewSkip: false,
      ruleApprovalNodes: [],
      currentNodeOID: '',
      skipNodeOID: '',
      loading: true,
      version: null,
      formOID: null,
      uploading: false,
    }
  }

  componentWillReceiveProps(nextProps) {
    let { showAdminSkipModal, showNewSkip } = this.state;
    // if (nextProps.isNew) {
    //   showNewSkip = nextProps.visible;
    // } else {
    //   showAdminSkipModal = nextProps.visible;
    // }
    if (nextProps.entityOID && nextProps.visible) {
      //详情的跳转需要调用接口判断是否是新版本
      this.setState({ loading: true });
      let params = {
        entityOID: nextProps.entityOID,
        entityType: nextProps.entityType
      };
      adminApproveListService.postNowDocumentBrms(params)
        .then(res => {
          this.setState({
            ruleApprovalNodes: res.data.ruleApprovalNodes,
            currentNodeOID: res.data.currentNodeOID,
            version: res.data.version,
            formOID: res.data.formOID,
            showAdminSkipModal:  !res.data.version || res.data.version.split('.')[0] === '0',
            showNewSkip: res.data.version && res.data.version.split('.')[0] > 0,
            loading: false,
          })
        }).catch(e => {
        this.setState({ loading: false });
        message.error(`${e.response.data.message}`)
      });
    } else if (nextProps.entityOID && nextProps.fromList && nextProps.visible) {
      if (nextProps.isNew) {
        showNewSkip = nextProps.visible;
      } else {
        showAdminSkipModal = nextProps.visible;
      }
      this.setState({
        ruleApprovalNodes: nextProps.ruleApprovalNodes,
        currentNodeOID: nextProps.currentNodeOID,
        version: nextProps.version,
        formOID: nextProps.formOID,
        showAdminSkipModal,
        showNewSkip,
      })
    }
  }

  onOk = () => {
    if (this.state.skipNodeOID === '') {
      message.warning(messages('setting.key882'/*请选择要跳转的流程*/));
      return;
    }
    this.setState({ uploading: true });
    let params = {
      entityOID: this.props.entityOID,
      entityType: this.props.entityType,
      currentNodeOID: this.props.isNew ? this.props.currentNodeOID : this.state.currentNodeOID,
      skipNodeOID: this.state.skipNodeOID,
    };
    adminApproveListService.postSkipDocumentBrms(params)
      .then(res => {
        this.setState({ showAdminSkipModal: false, showNewSkip: false, uploading: false, skipNodeOID: '', currentNodeOID: '' },
          () => {
            message.success(messages('setting.key883'/*跳转成功*/));
            this.afterClose('success');
          });
      })
      .catch(e => {
        this.setState({ uploading: false });
        this.afterClose('error');
        message.error(messages('setting.key1466', { arg1: !!e.response.data.message ? e.response.data.message : messages('common.error') }/*操作失败，{arg1}*/))
      })

  };

  // componentWillUnmount() {
  //   //重写组件的state
  //   this.setState = (state, callback) => {
  //     return;
  //   };
  // }

  afterClose = res => {
    this.props.afterClose(res);
  }

  onCancel = () => {
    this.afterClose('cancel');
    this.setState({ showAdminSkipModal: false, showNewSkip: false, uploading: false, skipNodeOID: '', currentNodeOID: '' });
  };

  //获取节点图片
  getNodeImg = type => {
    switch(type) {
      case 1001:  //审批
        return <img src={manApprovalImg} className="node-img"/>;
      case 1002:  //知会
        return <img src={knowImg} className="node-img"/>;
      case 1003:  //机器人
        return <img src={aiApprovalImg} className="node-img"/>;
      case 1004:  //发送打印
        return <img src={mailImg} className="node-img"/>;
      case 1006:  //审核
        return <img src={auditImg} className="node-img"/>;
      case 1005:  //结束
        return <img src={endImg} className="node-img"/>;
      case 1007:  //信用审批
        return <img src={creditImg} className="node-img"/>
    }
  };
  handleSkip = (node, index) => {
    this.state.ruleApprovalNodes.map((item, i) => {
      item.selected = false;
      if (i === index && item.type === 1001) {
        item.selected = true;
        this.setState({
          skipNodeOID: item.ruleApprovalNodeOID
        })
      }
    });
    this.setState({
      ruleApprovalNodes: this.state.ruleApprovalNodes
    })
  };

  handleSuccess = skipNodeOID => {
    if (!skipNodeOID) {
      message.error(messages('setting.key2014')/*请选择一个节点进行跳转*/);
      return;
    }
    this.setState({ skipNodeOID },()=>{
      this.onOk();
    })
  };

  handleCancel = () => {
    this.afterClose('cancel');
    this.setState({ showAdminSkipModal: false, showNewSkip: false, skipNodeOID: '', currentNodeOID: '', version: null })
  };

  render() {
    const { showAdminSkipModal, ruleApprovalNodes, currentNodeOID, uploading, loading, showNewSkip, version, formOID } = this.state;
    return (
      <div>
        { showNewSkip &&
        <FullScreen animateIn="fadeIn" animateOut="fadeOut" style={{ background: '#E3E5E8' }}>
          <NewWorkflowDetail
            nodeList={allNodeList}
            version={version}
            currentNodeOID={currentNodeOID}
            onSuccess={this.handleSuccess}
            onCancel={this.handleCancel}
            readOnly
            formOID={formOID}
          />
        </FullScreen>
        }
        {
          showAdminSkipModal && <Modal title={messages('setting.key881'/*跳转至*/)}
                                       width="50%"
                                       onCancel={this.onCancel}
                                       onOk={this.onOk}
                                       confirmLoading={uploading}
                                       visible={showAdminSkipModal}>
            <div className="admin-skip-wrap">
              <Icon type="info-circle" className="info"/> {messages('setting.key884'/*只能对人工审批环节进行跳转*/)}
              <Spin spinning={loading}>
                <div className="admin-skip">
                  {
                    ruleApprovalNodes && !!ruleApprovalNodes.length && ruleApprovalNodes.map((node, index) => {
                        return (
                          <div onClick={() => {this.handleSkip(node, index)}} className="node-wrap" key={index}>
                            {node.ruleApprovalNodeOID === currentNodeOID &&
                            <span className="node-current">{messages('setting.key885'/*当前*/)}</span>}
                            {node.selected &&
                            <span className="node-selected"><Icon className="selected-icon" type="check"/></span>}
                            {this.getNodeImg(node.type)}
                            {index < ruleApprovalNodes.length - 1 && <Icon type="arrow-right" className="right-arrow"/>}
                            <span
                              className="node-text">{node.type === 1005 ? messages('setting.key1252'/*结束*/) : node.remark}</span>
                          </div>)
                      }
                    )}
                </div>
              </Spin>
            </div>
          </Modal>
        }
      </div>

    )
  }
}

AdminSkip.propTypes = {
  visible: React.PropTypes.bool,           //导入弹框是否可见
  title: React.PropTypes.string,      //标题
  onOk: React.PropTypes.func,       //导入成功回调
  afterClose: React.PropTypes.func,//关闭后的回调
  reportOID: React.PropTypes.string, //单据OID
  formOID: React.PropTypes.string,    //表单oid
  userOID: React.PropTypes.string,  //用户OID
  entityOID: React.PropTypes.string,  //单据OID
  entityType: React.PropTypes.number,  //单据类型
  fromList: React.PropTypes.bool, //是否是新版审批
  isNew: React.PropTypes.bool, //是否是新版审批
  version: React.PropTypes.string,  //当前节点oid
  currentNodeOID: React.PropTypes.string,  //当前节点oid
};

AdminSkip.defaultProps = {
  title: messages('setting.key881'/*跳转至*/),
  reportOID: null,
  formOID: null,
  userOID: null,
  onOk: () => {
  },
  afterClose: () => {
  },
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    language: state.main.language,
    approveRequest: state.cache.approveRequest,
  }
}

const wrappedAdminSkip = Form.create()(AdminSkip);

export default connect(mapStateToProps)(wrappedAdminSkip)
